package codeTop;

public class q4 {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            int[] temp = nums1;
            nums1 = nums2;
            nums2 = temp;
        }
        int m = nums1.length;
        int n = nums2.length;
        int leftLen = (m+n+1)/2;
        int left = 0;
        int right = m;
        while (left < right) {
            int i = (left+right+1)/2;
            int j = leftLen-i;
            if (nums1[i-1]>nums2[j]){
                right = i-1;
            }else {
                left = i;
            }
        }
        int i = (left+right+1)/2;
        int j = leftLen-i;
        int a = i==0?Integer.MIN_VALUE:nums1[i-1];
        int b = i==m?Integer.MAX_VALUE:nums1[i];
        int c = j==0?Integer.MIN_VALUE:nums2[j-1];
        int d = j==n?Integer.MAX_VALUE:nums2[j];
        if ((m + n) % 2 == 1) {
            return Math.max(a,c);
        }else {
            return (double) (Math.max(a,c)+Math.min(b,d))/2;
        }
    }
}
